package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    /**
     * 把cookie设置到浏览器中
     * @param resp
     * @param key
     * @param value
     * @param time
     */
    public static void addCookie(HttpServletResponse resp,String key,String value,int time){
        //4.创建一个Cookie,将token设置到cookie后通过response对象带到浏览器.并且设置过时时间\
        Cookie cookie = new Cookie(key,value);
        //4.1设置共享路径
        cookie.setPath("/");
        //4.2设置时效
        cookie.setMaxAge(time);
        resp.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest req, HttpServletResponse resp){
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    //token = cookie.getValue();
                    //延时
                    cookie.setMaxAge(RedisKeys.USER_LOGIN.getTime().intValue());
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
